<template>
  <div class="page-container home">
    <div class="home-list" v-if="menu">
      <template v-for="(child, index) in menu.children">
        <div class="home-list" :key="child.path + '_' + index" v-if="child.children && child.children.length > 0">
          <el-divider class="home-line" content-position="left">{{ child.meta.title }}</el-divider>

          <div class="home-list-item" v-for="(item, k) in child.children" :key="item.path + '_' + k" @click="onClick(child.path, item)">
            <svg-icon
              v-if="item.meta && item.meta.icon && item.meta.icon !== '#'"
              :icon-class="item.meta.icon"/>
            <div class="home-list-item__name">{{ item.meta.title }}</div>
          </div>
        </div>
        <div v-else :key="child.path + '_' + index" class="home-list-item" @click="onClick('', child)">
          <svg-icon
            v-if="child.meta && child.meta.icon && child.meta.icon !== '#'"
            :icon-class="child.meta.icon"/>
          <div class="home-list-item__name">{{ child.meta.title }}</div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import {isExternal} from "@/utils/validate";
import path from "path";

const KEY = 'HOME_KEY'

export default {
  name: 'home',
  data() {
    return {
      menu: null
    }
  },
  methods: {
    init() {
      const data = sessionStorage.getItem(KEY)
      this.menu = JSON.parse(data)
      this.$tab.updatePage({path: '/home/index', title: this.menu.meta.title})
    },
    onClick(basePath, item) {
      const menuPath = this.resolvePath('', this.menu.path)
      let _path = item.path
      if(basePath) {
        _path = basePath + '/' + _path
      }

      const to = this.resolvePath(menuPath, _path, item.query)
      this.$router.push(to)
    },
    resolvePath(basePath, routePath, routeQuery) {
      if (isExternal(routePath)) {
        return routePath
      }
      if (isExternal(basePath)) {
        return basePath
      }
      if (routeQuery) {
        let query = JSON.parse(routeQuery);
        return { path: path.resolve(basePath, routePath), query: query }
      }
      return path.resolve(basePath, routePath)
    }
  },
  watch: {
    $route() {
      this.init()
    }
  },
  mounted() {
    this.init()
  }
}
</script>
<style scoped lang="scss">
.home {
  padding: 20px;

  &-list {
    position: relative;
    color: #08326e;

    &-item {
      display: inline-block;
      width: 100px;
      text-align: center;
      margin-right: 15px;
      font-size: 30px;
      cursor: pointer;
      border-right: 8px;
      border-radius: 2px;

      &:hover {
        background-color: #0a397c;
        color: #FFF;
      }

      &__name {
        margin: 5px 0;
        font-size: 12px;
      }
    }
  }

  &-line {
    position: relative;
    background-color: #94b4ff;
    font-size: 12px;

    & > span {
      &::after {
        position: absolute;
      }
    }
  }


}
</style>
